import "dart:convert";
import "dart:math";

import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/mine/withdraw/api.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:flutter/material.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";

class WithdrawPage extends StatefulWidget {
  final int apartmentId;
  const WithdrawPage({super.key, required this.apartmentId});

  @override
  State<WithdrawPage> createState() => _WithdrawPageState();
}

class _WithdrawPageState extends State<WithdrawPage> {
  final ScrollController _scrollController = ScrollController();
  final Map<String, dynamic> _filter = {
    "pageNum": 1,
    "pageSize": 10,
    "apartmentId": 0,
  };
  int _apartmentId = -1;

  
  // 模拟数据
  double _availableAmount = 0;
  List _billList = [];
  bool _isLoading = false;
  bool _hasMore = true;
  bool _disposed = false; // 添加销毁标志

  // 获取未提现金额
  Future<void> _getUnwithdrawAmount() async {
    if (_apartmentId == 0) {
      return;
    }
    // 这里需要调用获取未提现金额
    Map result = await billApi.getUnwithdrawAmount(_apartmentId);
    setState(() {
      _availableAmount = result["data"] ?? 0.0;
    });
  }

  @override
  void initState() {
    super.initState();
    
    String apartment = storage.getString("apartment") ?? "";
    if (apartment != "") {
      _apartmentId = jsonDecode(apartment)["apartmentId"] ?? -1;
    }
    
    // 只有在有效的apartmentId时才加载数据
    if (_apartmentId > 0) {
      _filter["apartmentId"] = _apartmentId;
      print("apartmentId>>>>$_apartmentId");
      _loadMockData();
      _getUnwithdrawAmount();
    } else {
      // 如果没有有效的apartmentId，设置没有更多数据
      _hasMore = false;
    }
    
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _disposed = true;
    _scrollController.dispose();
    super.dispose();
  }

  // 加载模拟数据
  void _loadMockData() {
    // 检查apartmentId是否有效
    if (_apartmentId <= 0 || _disposed) {
      setState(() {
        _isLoading = false;
        _hasMore = false;
      });
      return;
    }
    
    setState(() {
      _isLoading = true;
    });
    
    billApi.getUnwithdrawBillList(_filter).then((value) {
      setState(() {
        _isLoading = false;
        List newList = value["data"]["bills"] ?? [];
        if (_filter["pageNum"] == 1) {
          // 第一页，直接替换数据
          _billList = newList;
        } else {
          // 加载更多，追加数据
          _billList.addAll(newList);
        }

        // 判断是否还有更多数据
        _hasMore = newList.length >= _filter["pageSize"];
      });
    }).catchError((error) {
      if (mounted && !_disposed) {
        setState(() {
          _isLoading = false;
          // 如果是加载更多失败，回退页码
          if (_filter["pageNum"] > 1) {
            _filter["pageNum"] = _filter["pageNum"] - 1;
          }
        });
      }
    });
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    // 检查apartmentId是否有效
    if (_apartmentId <= 0 || _disposed) {
      return;
    }
    
    setState(() {
      _filter["pageNum"] = 1;
      _billList.clear();
      _hasMore = true;
    });
    _loadMockData();
    _getUnwithdrawAmount();
  }

  // 上拉加载更多
  void _onScroll() {
    if (!mounted || _disposed || _apartmentId <= 0) return;
    
    // 添加防抖，避免重复触发
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) {
      if (_hasMore && !_isLoading) {
        // 添加一个小延迟，避免快速滚动时重复触发
        Future.delayed(const Duration(milliseconds: 100), () {
          if (mounted && !_disposed && _hasMore && !_isLoading && _apartmentId > 0) {
            _loadMore();
          }
        });
      }
    }
  }

  void _loadMore() {
    if (!_hasMore || _isLoading || _disposed || _apartmentId <= 0) return;
    
    setState(() {
      _filter["pageNum"] = _filter["pageNum"] + 1;
    });
    
    _loadMockData();
  }

  /* 提现 */
  void _withdraw() {
    withdrawApi.withdraw({ "apartmentId": _apartmentId }).then((value) {
      EasyLoading.showSuccess("提现申请已提交，请等待处理");
      _onRefresh();
    });
  }

  // 提现操作
  void _handleWithdraw() {
    if (_availableAmount <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("可提现金额不足")),
      );
      return;
    }

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("确认提现"),
          content: Text("确定要提现 ¥${Utils.formatCurrency(_availableAmount)} 吗？"),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text("取消"),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _withdraw();
              },
              child: const Text("确定"),
            ),
          ],
        );
      },
    );
  }

  // 跳转到提现记录
  void _goToWithdrawList() {
    Stacker.pushNamed(Keys.WITHDRAW_LIST);
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "提现",
      actions: [
        TextButton(
          onPressed: _goToWithdrawList,
          child: const Text("提现记录", style: TextStyle(color: Colors.white),),
        ),
      ],
      child: Stack(
        children: [
          // 主要内容区域
          RefreshIndicator(
            onRefresh: _onRefresh,
            child: ListView(
              controller: _scrollController,
              padding: const EdgeInsets.only(bottom: 80), // 为底部按钮留出空间
              children: [
                // 可提现金额卡片
                Container(
                  margin: const EdgeInsets.all(ThemeVars.paddingPage),
                  padding: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      const Text(
                        "可提现金额",
                        style: TextStyle(
                          fontSize: 14,
                          color: ThemeVars.colorTextSec,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        "¥${Utils.formatCurrency(_availableAmount)}",
                        style: const TextStyle(
                          fontSize: 28,
                          fontWeight: FontWeight.bold,
                          color: ThemeVars.colorPrimary,
                        ),
                      ),
                      const SizedBox(height: 16),
                      SizedBox(
                        width: double.infinity,
                        child: Button(
                          type: ButtonType.primary,
                          size: ButtonSize.large,
                          onPressed: _availableAmount > 0 ? _handleWithdraw : null,
                          child: const Text("立即提现"),
                        ),
                      ),
                    ],
                  ),
                ),

                // 未提现账单列表
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Padding(
                        padding: EdgeInsets.symmetric(vertical: 12),
                        child: Text(
                          "未提现账单",
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      if (_billList.isEmpty)
                        Container(
                          padding: const EdgeInsets.all(40),
                          child: Center(
                            child: Column(
                              children: [
                                Icon(
                                  _isLoading ? Icons.hourglass_empty : Icons.receipt_long,
                                  size: 48,
                                  color: ThemeVars.colorTextTer,
                                ),
                                const SizedBox(height: 16),
                                Text(
                                  _apartmentId <= 0 
                                    ? "无效的公寓ID"
                                    : _isLoading 
                                      ? "加载中..."
                                      : "暂无未提现账单",
                                  style: const TextStyle(
                                    color: ThemeVars.colorTextSec,
                                    fontSize: 14,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      else
                        ..._billList.map((bill) => _buildBillItem(bill)),
                      
                      // 加载更多指示器
                      if (_isLoading)
                        const Padding(
                          padding: EdgeInsets.all(16),
                          child: Center(
                            child: CircularProgressIndicator(),
                          ),
                        ),
                      
                      // 没有更多数据提示
                      if (!_hasMore && _billList.isNotEmpty)
                        const Padding(
                          padding: EdgeInsets.all(16),
                          child: Center(
                            child: Text(
                              "没有更多数据了",
                              style: TextStyle(
                                color: ThemeVars.colorTextSec,
                                fontSize: 14,
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建账单项
  Widget _buildBillItem(Map<String, dynamic> bill) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: ThemeVars.colorBorder,
          width: 0.5,
        ),
      ),
      child: Column(
        children: [
          // 中间内容
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                bill["name"] ?? "--",
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Text(
                "¥${bill["money"]}",
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: ThemeVars.colorSuccess,
                ),
              ),
            ],
          ),
          // 右侧金额和状态
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                bill["createTime"],
                style: const TextStyle(
                  fontSize: 12,
                  color: ThemeVars.colorTextSec,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
